<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Python," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="Python 字符串&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;字符串是 Python 中最常用的数据类型。可以使用引号（‘’或“”）来创建字符串。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;创建字符串很简单，只要为变量分配一个值即可。例如： 12var1 = &apos;hello world&apos;var">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="Python 字符串">
<meta property="og:url" content="https://hcldirgit.github.io/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.5 Python 的数值和字符串/7. Python 字符串/index.html">
<meta property="og:site_name" content="失落的乐章">
<meta property="og:description" content="Python 字符串&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;字符串是 Python 中最常用的数据类型。可以使用引号（‘’或“”）来创建字符串。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;创建字符串很简单，只要为变量分配一个值即可。例如： 12var1 = &apos;hello world&apos;var">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://github.com/hcldirgit/image/blob/master/python%E5%AD%97%E7%AC%A6%E4%B8%B2/01.png?raw=true">
<meta property="og:updated_time" content="2017-08-10T05:55:04.243Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python 字符串">
<meta name="twitter:description" content="Python 字符串&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;字符串是 Python 中最常用的数据类型。可以使用引号（‘’或“”）来创建字符串。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;创建字符串很简单，只要为变量分配一个值即可。例如： 12var1 = &apos;hello world&apos;var">
<meta name="twitter:image" content="https://github.com/hcldirgit/image/blob/master/python%E5%AD%97%E7%AC%A6%E4%B8%B2/01.png?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://hcldirgit.github.io/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.5 Python 的数值和字符串/7. Python 字符串/"/>





  <title>Python 字符串 | 失落的乐章</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', '85*****1', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?87980c**************99ec5e26fb5";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>











  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">失落的乐章</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">技术面前，永远都是学生。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-message">
          <a href="/message" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-external-link"></i> <br />
            
            留言
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://hcldirgit.github.io/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.5 Python 的数值和字符串/7. Python 字符串/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="失落的乐章">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/0.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="失落的乐章">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python 字符串</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-10T14:00:36+08:00">
                2017-08-10
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Python-字符串"><a href="#Python-字符串" class="headerlink" title="Python 字符串"></a>Python 字符串</h1><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;字符串是 Python 中最常用的数据类型。可以使用引号（‘’或“”）来创建字符串。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;创建字符串很简单，只要为变量分配一个值即可。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">var1 = <span class="string">'hello world'</span></div><div class="line">var2 = <span class="string">"python runoob"</span></div></pre></td></tr></table></figure>
<h2 id="Python-访问字符串中的值"><a href="#Python-访问字符串中的值" class="headerlink" title="Python 访问字符串中的值"></a>Python 访问字符串中的值</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Python 不支持单字符类型，单字符在 Python 也是作为一个字符串使用。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Python 访问子字符串，可以使用方括号来截取字符串，如下实例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"></div><div class="line">var1 = <span class="string">'Hello World!'</span></div><div class="line">var2 = <span class="string">"Python Runoob"</span></div><div class="line"></div><div class="line"><span class="keyword">print</span> <span class="string">"var1[0]: "</span>, var1[<span class="number">0</span>]</div><div class="line"><span class="keyword">print</span> <span class="string">"var2[1:5]: "</span>, var2[<span class="number">1</span>:<span class="number">5</span>]</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;以上实例执行结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">var1[<span class="number">0</span>]:  H</div><div class="line">var2[<span class="number">1</span>:<span class="number">5</span>]:   ytho</div></pre></td></tr></table></figure>
<h2 id="Python-字符串更新"><a href="#Python-字符串更新" class="headerlink" title="Python 字符串更新"></a>Python 字符串更新</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;可以对已存在的字符串进行修改，并赋值给另一个变量，如下实例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"><span class="comment"># -*- coding: UTF-8 -*-</span></div><div class="line"></div><div class="line">var1 = <span class="string">'Hello World!'</span></div><div class="line"></div><div class="line"><span class="keyword">print</span> <span class="string">"更新字符串 :- "</span>, var1[:<span class="number">6</span>] + <span class="string">'Runoob!'</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;以上实例执行结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">更新字符串 ：- Hello Runoob!</div></pre></td></tr></table></figure>
<h2 id="Python-转义字符"><a href="#Python-转义字符" class="headerlink" title="Python 转义字符"></a>Python 转义字符</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;当需要在字符中使用特殊字符时，Python 用反斜杠（\）转义字符。如下表：</p>
<table>
<thead>
<tr>
<th>转义字符</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>\（在行尾时）</td>
<td>续行符</td>
</tr>
<tr>
<td>\\</td>
<td>反斜杠符号</td>
</tr>
<tr>
<td>\‘</td>
<td>反引号</td>
</tr>
<tr>
<td>\“</td>
<td>双引号</td>
</tr>
<tr>
<td>\a</td>
<td>响铃</td>
</tr>
<tr>
<td>\b</td>
<td>退格（Backspace）</td>
</tr>
<tr>
<td>\e</td>
<td>转义</td>
</tr>
<tr>
<td>\000</td>
<td>空</td>
</tr>
<tr>
<td>\n</td>
<td>换行</td>
</tr>
<tr>
<td>\v</td>
<td>纵向制表符</td>
</tr>
<tr>
<td>\t</td>
<td>横向制表符</td>
</tr>
<tr>
<td>\r</td>
<td>回车</td>
</tr>
<tr>
<td>\f</td>
<td>换页</td>
</tr>
<tr>
<td>\oyy</td>
<td>八进制数，yy代表的字符，例如：\o12 代表换行</td>
</tr>
<tr>
<td>\xyy</td>
<td>十六进制数，yy代表的字符，例如：\x0a代表换行</td>
</tr>
<tr>
<td>\other</td>
<td>其他的字符以普通格式输出</td>
</tr>
</tbody>
</table>
<h2 id="Python-字符串运算符"><a href="#Python-字符串运算符" class="headerlink" title="Python 字符串运算符"></a>Python 字符串运算符</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;下表实例变量 a 值为字符串 “Hello”，b 变量为 “Python”：</p>
<p><img src="https://github.com/hcldirgit/image/blob/master/python%E5%AD%97%E7%AC%A6%E4%B8%B2/01.png?raw=true" alt="images"></p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;实例如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"><span class="comment"># -*- coding: UTF-8 -*-</span></div><div class="line"></div><div class="line">a = <span class="string">"Hello"</span></div><div class="line">b = <span class="string">"Python"</span></div><div class="line"></div><div class="line"><span class="keyword">print</span> <span class="string">"a + b 输出结果："</span>, a + b </div><div class="line"><span class="keyword">print</span> <span class="string">"a * 2 输出结果："</span>, a * <span class="number">2</span> </div><div class="line"><span class="keyword">print</span> <span class="string">"a[1] 输出结果："</span>, a[<span class="number">1</span>] </div><div class="line"><span class="keyword">print</span> <span class="string">"a[1:4] 输出结果："</span>, a[<span class="number">1</span>:<span class="number">4</span>] </div><div class="line"></div><div class="line"><span class="keyword">if</span>( <span class="string">"H"</span> <span class="keyword">in</span> a) :</div><div class="line">    <span class="keyword">print</span> <span class="string">"H 在变量 a 中"</span> </div><div class="line"><span class="keyword">else</span> :</div><div class="line">	<span class="keyword">print</span> <span class="string">"H 不在变量 a 中"</span> </div><div class="line"></div><div class="line"><span class="keyword">if</span>( <span class="string">"M"</span> <span class="keyword">not</span> <span class="keyword">in</span> a) :</div><div class="line">    <span class="keyword">print</span> <span class="string">"M 不在变量 a 中"</span> </div><div class="line"><span class="keyword">else</span> :</div><div class="line">	<span class="keyword">print</span> <span class="string">"M 在变量 a 中"</span></div><div class="line"></div><div class="line"><span class="keyword">print</span> <span class="string">r'\n'</span></div><div class="line"><span class="keyword">print</span> R<span class="string">'\n'</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;以上程序执行结果为：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">a + b 输出结果： HelloPython</div><div class="line">a * <span class="number">2</span> 输出结果： HelloHello</div><div class="line">a[<span class="number">1</span>] 输出结果： e</div><div class="line">a[<span class="number">1</span>:<span class="number">4</span>] 输出结果： ell</div><div class="line">H 在变量 a 中</div><div class="line">M 不在变量 a 中</div><div class="line">\n</div><div class="line">\n</div></pre></td></tr></table></figure>
<h2 id="Python-字符串格式化"><a href="#Python-字符串格式化" class="headerlink" title="Python 字符串格式化"></a>Python 字符串格式化</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Python 支持格式化字符串的输出，尽管这样可能会用到非常复杂发表达式，但最基本的用法是将一个值插入到有一个有字符串格式符 %s 发字符串中。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在 Python 中，字符串格式化使用与 C 中 sprintf函数一样的语法。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如下实例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"></div><div class="line"><span class="keyword">print</span> <span class="string">"My name is %s and weight is %d kg!"</span> % (<span class="string">'Zara'</span>,<span class="number">21</span>)</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;以上实例输出结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">My name <span class="keyword">is</span> Zara <span class="keyword">and</span> weight <span class="keyword">is</span> <span class="number">21</span> kg!</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;python 字符串格式化符号：</p>
<table>
<thead>
<tr>
<th>符号</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>%c</td>
<td>格式化字符及其ASCII码</td>
</tr>
<tr>
<td>%s</td>
<td>格式化字符串</td>
</tr>
<tr>
<td>%d</td>
<td>格式化整数</td>
</tr>
<tr>
<td>%u</td>
<td>格式化无符号整型</td>
</tr>
<tr>
<td>%o</td>
<td>格式化无符号八进制数</td>
</tr>
<tr>
<td>%x</td>
<td>格式化无符号十六进制数</td>
</tr>
<tr>
<td>%X</td>
<td>格式化无符号十六进制数（大写）</td>
</tr>
<tr>
<td>%f</td>
<td>格式化浮点数字，可指定小数点后的精度</td>
</tr>
<tr>
<td>%e</td>
<td>用科学计数法格式化浮点数</td>
</tr>
<tr>
<td>%E</td>
<td>作用同 %e ，用科学计数法格式化浮点数</td>
</tr>
<tr>
<td>%g</td>
<td>%f 和 %e 的简写</td>
</tr>
<tr>
<td>%G</td>
<td>%f 和 %E 的简写</td>
</tr>
<tr>
<td>%p</td>
<td>用十六进制数格式化变量的地址</td>
</tr>
</tbody>
</table>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;格式化操作符辅助指令：</p>
<table>
<thead>
<tr>
<th>符号</th>
<th>功能</th>
</tr>
</thead>
<tbody>
<tr>
<td>*</td>
<td>定义宽度或者小数点精度</td>
</tr>
<tr>
<td>-</td>
<td>用作左对齐</td>
</tr>
<tr>
<td>+</td>
<td>在正数前面显示加号（+）</td>
</tr>
<tr>
<td><sp></sp></td>
<td>在正数前面显示空格</td>
</tr>
<tr>
<td>#</td>
<td>在八进制数前面显示零（‘0’），在十六进制数前显示‘0x’或者‘0X’（取决于用的是‘x’还是‘X’）</td>
</tr>
<tr>
<td>0</td>
<td>显示的数字前面填充‘0’而不是默认的空格</td>
</tr>
<tr>
<td>%</td>
<td>‘%%’输出一个单一的‘%’</td>
</tr>
<tr>
<td>（var）</td>
<td>映射变量（字典参数）</td>
</tr>
<tr>
<td>m.n.</td>
<td>m 是显示的最小总宽度，n 是小数点后的位数(如果可用的话)</td>
</tr>
</tbody>
</table>
<h2 id="Python-三引号（triple-quotes）"><a href="#Python-三引号（triple-quotes）" class="headerlink" title="Python 三引号（triple quotes）"></a>Python 三引号（triple quotes）</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;python 中三引号可以将复杂的字符串进行复制：</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;python 三引号允许一个字符串跨多行，字符串中可以包含换行符、制表符以及其他特殊字符。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;三引号的语法是一对连续的单引号或者双引号（通常都是成对的用）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span>hi = <span class="string">'''hi</span></div><div class="line"><span class="string">there'''</span></div><div class="line"><span class="meta">&gt;&gt;&gt; </span>hi <span class="comment">#repr()</span></div><div class="line"><span class="string">'hi\nthere'</span></div><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">print</span> hi <span class="comment"># str()</span></div><div class="line">hi</div><div class="line">there</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;三引号让程序员从引号和特殊字符串的泥潭里面解脱出来，自始至终宝石一小块字符串的格式是所谓的WYSIWYG（所见即所得）格式的。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;一个典型的用例是，当需要一块 HTML 或者SQL时，这是用字符串组合，特殊字符串转义将会非常的繁琐。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">errHTML = <span class="string">'''</span></div><div class="line"><span class="string">&lt;HTML&gt;&lt;HEAD&gt;&lt;TITLE&gt;</span></div><div class="line"><span class="string">Friends CGI Demo&lt;/TITLE&gt;&lt;/HEAD&gt;</span></div><div class="line"><span class="string">&lt;BODY&gt;&lt;H3&gt;ERROR&lt;/H3&gt;</span></div><div class="line"><span class="string">&lt;B&gt;%s&lt;/B&gt;&lt;P&gt;</span></div><div class="line"><span class="string">&lt;FORM&gt;&lt;INPUT TYPE=button VALUE=Back</span></div><div class="line"><span class="string">ONCLICK="window.history.back()"&gt;&lt;/FORM&gt;</span></div><div class="line"><span class="string">&lt;/BODY&gt;&lt;/HTML&gt;</span></div><div class="line"><span class="string">'''</span></div><div class="line">cursor.execute(<span class="string">'''</span></div><div class="line"><span class="string">CREATE TABLE users (  </span></div><div class="line"><span class="string">login VARCHAR(8), </span></div><div class="line"><span class="string">uid INTEGER,</span></div><div class="line"><span class="string">prid INTEGER)</span></div><div class="line"><span class="string">'''</span>)</div></pre></td></tr></table></figure>
<h2 id="Unicode-字符串"><a href="#Unicode-字符串" class="headerlink" title="Unicode 字符串"></a>Unicode 字符串</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Python 中定义一个 Unicode 字符串和定义一个普通字符串一样简单：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">u'Hello World !'</span></div><div class="line"><span class="string">u'Hello World !'</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;引号前小写的”u”表示这里创建的是一个 Unicode 字符串。如果你想加入一个特殊字符，可以使用 Python 的 Unicode-Escape 编码。如下例所示：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">u'Hello\u0020World !'</span></div><div class="line"><span class="string">u'Hello World !'</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;被替换的 \u0020 标识表示在给定位置插入编码值为 0x0020 的 Unicode 字符（空格符）。</p>
<h2 id="python-的字符串内建函数"><a href="#python-的字符串内建函数" class="headerlink" title="python 的字符串内建函数"></a>python 的字符串内建函数</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;字符串方法是从python1.6到2.0慢慢加进来的——它们也被加到了Jython中。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这些方法实现了string模块的大部分方法，如下表所示列出了目前字符串内建支持的方法，所有的方法都包含了对Unicode的支持，有一些甚至是专门用于Unicode的。</p>
<table>
<thead>
<tr>
<th>方法</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>string.capitalize()</td>
<td>把字符串的第一个字符大写</td>
</tr>
<tr>
<td>string.center(width)</td>
<td>返回一个原字符串居中,并使用空格填充至长度 width 的新字符串</td>
</tr>
<tr>
<td>string.count(str, beg=0, end=len(string))</td>
<td>返回 str 在 string 里面出现的次数，如果 beg 或者 end 指定则返回指定范围内 str 出现的次数</td>
</tr>
<tr>
<td>string.decode(encoding=’UTF-8’, errors=’strict’)</td>
<td>以 encoding 指定的编码格式解码 string，如果出错默认报一个 ValueError 的 异 常 ， 除 非 errors 指 定 的 是 ‘ignore’ 或 者’replace’</td>
</tr>
<tr>
<td>string.encode(encoding=’UTF-8’, errors=’strict’)</td>
<td>以 encoding 指定的编码格式编码 string，如果出错默认报一个ValueError 的异常，除非 errors 指定的是’ignore’或者’replace’</td>
</tr>
<tr>
<td>string.endswith(obj, beg=0, end=len(string))</td>
<td>检查字符串是否以 obj 结束，如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束，如果是，返回 True,否则返回 False.</td>
</tr>
<tr>
<td>string.expandtabs(tabsize=8)</td>
<td>把字符串 string 中的 tab 符号转为空格，tab 符号默认的空格数是 8。</td>
</tr>
<tr>
<td>string.find(str, beg=0, end=len(string))</td>
<td>检测 str 是否包含在 string 中，如果 beg 和 end 指定范围，则检查是否包含在指定范围内，如果是返回开始的索引值，否则返回-1</td>
</tr>
<tr>
<td>string.format()</td>
<td>格式化字符串</td>
</tr>
<tr>
<td>string.index(str, beg=0, end=len(string))</td>
<td>跟find()方法一样，只不过如果str不在 string中会报一个异常.</td>
</tr>
<tr>
<td>string.isalnum()</td>
<td>如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False</td>
</tr>
<tr>
<td>string.isalpha()</td>
<td>如果 string 至少有一个字符并且所有字符都是字母则返回 True,否则返回 False</td>
</tr>
<tr>
<td>string.isdecimal()</td>
<td>如果 string 只包含十进制数字则返回 True 否则返回 False.</td>
</tr>
<tr>
<td>string.isdigit()</td>
<td>如果 string 只包含数字则返回 True 否则返回 False.</td>
</tr>
<tr>
<td>string.islower()</td>
<td>如果 string 中包含至少一个区分大小写的字符，并且所有这些(区分大小写的)字符都是小写，则返回 True，否则返回 False</td>
</tr>
<tr>
<td>string.isnumeric()</td>
<td>如果 string 中只包含数字字符，则返回 True，否则返回 False</td>
</tr>
<tr>
<td>string.isspace()</td>
<td>如果 string 中只包含空格，则返回 True，否则返回 False.</td>
</tr>
<tr>
<td>string.istitle()</td>
<td>如果 string 是标题化的(见 title())则返回 True，否则返回 False</td>
</tr>
<tr>
<td>string.isupper()</td>
<td>如果 string 中包含至少一个区分大小写的字符，并且所有这些(区分大小写的)字符都是大写，则返回 True，否则返回 False</td>
</tr>
<tr>
<td>string.join(seq)</td>
<td>以 string 作为分隔符，将 seq 中所有的元素(的字符串表示)合并为一个新的字符串</td>
</tr>
<tr>
<td>string.ljust(width)</td>
<td>返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串</td>
</tr>
<tr>
<td>string.lower()</td>
<td>转换 string 中所有大写字符为小写.</td>
</tr>
<tr>
<td>string.lstrip()</td>
<td>截掉 string 左边的空格</td>
</tr>
<tr>
<td>string.maketrans(intab, outtab])</td>
<td>maketrans() 方法用于创建字符映射的转换表，对于接受两个参数的最简单的调用方式，第一个参数是字符串，表示需要转换的字符，第二个参数也是字符串表示转换的目标。</td>
</tr>
<tr>
<td>max(str)</td>
<td>返回字符串 str 中最大的字母。</td>
</tr>
<tr>
<td>min(str)</td>
<td>返回字符串 str 中最小的字母。</td>
</tr>
<tr>
<td>string.partition(str)</td>
<td>有点像 find()和 split()的结合体,从 str 出现的第一个位置起,把 字 符 串 string 分 成 一 个 3 元 素 的 元 组 (string_pre_str,str,string_post_str),如果 string 中不包含str 则 string_pre_str == string.</td>
</tr>
<tr>
<td>string.replace(str1, str2,  num=string.count(str1))</td>
<td>把 string 中的 str1 替换成 str2,如果 num 指定，则替换不超过 num 次.</td>
</tr>
<tr>
<td>string.rfind(str, beg=0,end=len(string) )</td>
<td>类似于 find()函数，不过是从右边开始查找.</td>
</tr>
<tr>
<td>string.rindex( str, beg=0,end=len(string))</td>
<td>类似于 index()，不过是从右边开始.</td>
</tr>
<tr>
<td>string.rjust(width)</td>
<td>返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串</td>
</tr>
<tr>
<td>string.rpartition(str)</td>
<td>类似于 partition()函数,不过是从右边开始查找.</td>
</tr>
<tr>
<td>string.rstrip()</td>
<td>删除 string 字符串末尾的空格.</td>
</tr>
<tr>
<td>string.split(str=””, num=string.count(str))</td>
<td>以 str 为分隔符切片 string，如果 num有指定值，则仅分隔 num 个子字符串</td>
</tr>
<tr>
<td>string.splitlines([keepends])</td>
<td>按照行(‘\r’, ‘\r\n’, \n’)分隔，返回一个包含各行作为元素的列表，如果参数 keepends 为 False，不包含换行符，如果为 True，则保留换行符。</td>
</tr>
<tr>
<td>string.startswith(obj, beg=0,end=len(string))</td>
<td>检查字符串是否是以 obj 开头，是则返回 True，否则返回 False。如果beg 和 end 指定值，则在指定范围内检查.</td>
</tr>
<tr>
<td>string.strip([obj])</td>
<td>在 string 上执行 lstrip()和 rstrip()</td>
</tr>
<tr>
<td>string.swapcase()</td>
<td>翻转 string 中的大小写</td>
</tr>
<tr>
<td>string.title()</td>
<td>返回”标题化”的 string,就是说所有单词都是以大写开始，其余字母均为小写(见 istitle())</td>
</tr>
<tr>
<td>string.translate(str, del=””)</td>
<td>根据 str 给出的表(包含 256 个字符)转换 string 的字符,要过滤掉的字符放到 del 参数中</td>
</tr>
<tr>
<td>string.upper()</td>
<td>转换 string 中的小写字母为大写</td>
</tr>
<tr>
<td>string.zfill(width)</td>
<td>返回长度为 width 的字符串，原字符串 string 右对齐，前面填充0</td>
</tr>
<tr>
<td>string.isdecimal()</td>
<td>isdecimal()方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。</td>
</tr>
</tbody>
</table>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.3 Python 的文件类型/4. Python 的文件类型/" rel="next" title="Python 的文件类型">
                <i class="fa fa-chevron-left"></i> Python 的文件类型
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.5 Python 的数值和字符串/6. Python 的数值/" rel="prev" title="Python 的数值">
                Python 的数值 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/0.png"
               alt="失落的乐章" />
          <p class="site-author-name" itemprop="name">失落的乐章</p>
           
              <p class="site-description motion-element" itemprop="description">失落的乐章的Blog</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/">
                <span class="site-state-item-count">627</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">38</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hcldirgit" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Python-字符串"><span class="nav-number">1.</span> <span class="nav-text">Python 字符串</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-访问字符串中的值"><span class="nav-number">1.1.</span> <span class="nav-text">Python 访问字符串中的值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-字符串更新"><span class="nav-number">1.2.</span> <span class="nav-text">Python 字符串更新</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-转义字符"><span class="nav-number">1.3.</span> <span class="nav-text">Python 转义字符</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-字符串运算符"><span class="nav-number">1.4.</span> <span class="nav-text">Python 字符串运算符</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-字符串格式化"><span class="nav-number">1.5.</span> <span class="nav-text">Python 字符串格式化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-三引号（triple-quotes）"><span class="nav-number">1.6.</span> <span class="nav-text">Python 三引号（triple quotes）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Unicode-字符串"><span class="nav-number">1.7.</span> <span class="nav-text">Unicode 字符串</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#python-的字符串内建函数"><span class="nav-number">1.8.</span> <span class="nav-text">python 的字符串内建函数</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">失落的乐章</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
